// Innitial map values
var map;
var directionsService;
var markers = [];

window.onload = function() {
	initialize();
}

function initialize() {
	// Set initial center position
	var latlng = new google.maps.LatLng(50.979865,4.081088);
	
	// Mapoptions
	var myOptions = {
		zoom:15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	// Initialize directionsService
	directionsService = new google.maps.DirectionsService();
	// Initialize map
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	// Add marker on click
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng);
	});

}

// Add marker to map on click
function addMarker(position) {
	if(markers.length < 10) {
		var request = {
			origin: position,
			destination: position,
			travelMode: google.maps.DirectionsTravelMode.WALKING
		};
		
		// Snap marker to road by calculating route to self
		directionsService.route(request, function(response, status) {
			var marker = new google.maps.Marker({
				position: response.routes[0].legs[0].start_location, 
				map: map,
				draggable: true
			});
			
			markers.push(marker);
		
			if(markers.length > 1) {
				calcRoute();
			}
		});
	}
}

function calcRoute() {
	var origin = markers[0].getPosition();
	var destination = markers[markers.length - 1].getPosition();
	var waypoints = [];
	
	if(markers.length > 2) {
		for(var i = 1; i < markers.position - 1; i++) {
			waypoints.push({
				location: markers[i].getPosition(),
				stopover: true
			});
		}
	}
	
	var directionsRequest = {
		origin: origin,
		waypoints: waypoints,
		destination: destination,
		travelMode: google.maps.DirectionsTravelMode.WALKING
	};
	
	var directionsRenderer = new google.maps.DirectionsRenderer({
		map: map,
		preserveViewport: true
	});
	
	directionsService.route(directionsRequest, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			showPath(response.routes[0].overview_path);
			var txt = document.getElementById('text');
			var val = txt.value;
		} else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
			alert("Could not find a route between these points");
		} else {
			alert("Directions request failed");
		}
	});
}

function showPath(path) {
	var polyline = new google.maps.Polyline({
		path: path,
		strokeColor: "#0066FF",
		map: map
	});
}